#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRegularExpression>
#include <QDateTime>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QValueAxis>
#include <csignal>  // 添加这个头文件
#include <QNetworkInterface>  // 网络接口相关
#include <QHostAddress>       // IP地址处理
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , ds9Process(nullptr)  // 初始化智能指针
{
    ui->setupUi(this);

    // DS9环境检测
    if(!detectDS9()) {
        QMessageBox::critical(this,
                              tr("DS9 Not Found"),
                              tr("SAOImage DS9 is required but not found.\n\n"
                                 "Please install it from:\n"
                                 "http://ds9.si.edu/download/"));

        // 非强制退出，改为禁用相关功能
        ui->checkboxShowFits->setEnabled(false);
        ui->checkboxShowFits->setToolTip(tr("DS9 not installed"));
    }

    initializeUI();
    // 禁用最大化按钮和大小调整
    //this->setWindowFlags(this->windowFlags() & ~Qt::WindowMaximizeButtonHint);
    //this->setFixedSize(this->size());
    setupPowerControlUI();
    initializeCharts();
    initStatusLeds();
    updateMasterLedStatus(false); // 设置初始指示灯状态
    initializeAlarmThresholds();
    qDebug() << "CCD1 Alarm Thresholds:"
             << ConfigManager::instance().ccd1MinTemp()
             << "-" << ConfigManager::instance().ccd1MaxTemp();
    //从配置文件初始化
    initializeFromConfig();
    // 初始化日志系统
    initializeLogSystem();

    // 初始化网络管理器

    //m_networkManager_304fits = new QNetworkAccessManager(this);
    m_networkManager = new QNetworkAccessManager(this);

    // 从配置加载服务器设置
    m_alertServerUrl = ConfigManager::instance().alertServerUrl();
    m_alertServerToken = ConfigManager::instance().alertServerToken();
    m_alertServerTimeout = ConfigManager::instance().alertServerTimeout();

    dataUpdateTimer = new QTimer(this);
    connect(dataUpdateTimer, &QTimer::timeout, this, [this](){
        updateTemperatureData();
        updateTemperatureCurves();    // 更新多曲线
        updateTemperatureDisplay();   // 更新多标签
        updateVacuumData();
        updateCameraStatus();
    });
    dataUpdateTimer->start(1000);

    exposureTimer = new QTimer(this);
    exposureTimer->setSingleShot(true);
    connect(exposureTimer, &QTimer::timeout, this, [this](){
        hwStatus.isExposing = false;
        hwStatus.cameraState = Idle;
        LOG_GENERAL("Exposure completed");
        updateCameraStatus();
    });



    disconnect(ui->btnStartExposure, nullptr, this, nullptr);
    disconnect(ui->btnSetReadoutRate, nullptr, this, nullptr);
    disconnect(ui->btnAbort, nullptr, this, nullptr);
    disconnect(ui->btnBrowsePath, nullptr, this, nullptr);
    disconnect(ui->btnPowerDown, nullptr, this, nullptr);
    disconnect(ui->btnPowerOn, nullptr, this, nullptr);
    disconnect(ui->btnShutterOff, nullptr, this, nullptr);
    disconnect(ui->btnShutterOn, nullptr, this, nullptr);
    disconnect(ui->btnReadIOStatus, nullptr, this, nullptr);

    disconnect(ui->btnmergefits, nullptr, this, nullptr);
    connect(ui->btnmergefits, &QPushButton::clicked, this, &MainWindow::on_btnmergefits_clicked);

    disconnect(ui->btnLinkToCamera, nullptr, this, nullptr);
    connect(ui->btnLinkToCamera, &QPushButton::clicked, this, &MainWindow::onLinkToCameraClicked);

    connect(ui->btnSetReadoutRate, &QPushButton::clicked, this, &MainWindow::on_btnSetReadoutRate_clicked);
    connect(ui->btnStartExposure, &QPushButton::clicked, this, &MainWindow::on_btnStartExposure_clicked);
    connect(ui->btnAbort, &QPushButton::clicked, this, &MainWindow::on_btnAbort_clicked);
    connect(ui->btnBrowsePath, &QPushButton::clicked, this, &MainWindow::on_btnBrowsePath_clicked);
    connect(ui->btnPowerDown, &QPushButton::clicked, this, &MainWindow::on_btnPowerDown_clicked);
    connect(ui->btnPowerOn, &QPushButton::clicked, this, &MainWindow::on_btnPowerOn_clicked);
    connect(ui->btnShutterOff, &QPushButton::clicked, this, &MainWindow::on_btnShutterOff_clicked);
    connect(ui->btnShutterOn, &QPushButton::clicked, this, &MainWindow::on_btnShutterOn_clicked);

    // 在MainWindow构造函数中连接信号槽
    connect(btnCameraPowerOn, &QPushButton::clicked, this, &MainWindow::on_btnCameraPowerOn_clicked);
    connect(btnCameraPowerOff, &QPushButton::clicked, this, &MainWindow::on_btnCameraPowerOff_clicked);
    connect(btnHeatPowerOn, &QPushButton::clicked, this, &MainWindow::on_btnHeatPowerOn_clicked);
    connect(btnHeatPowerOff, &QPushButton::clicked, this, &MainWindow::on_btnHeatPowerOff_clicked);
    connect(btnVaccuPowerOn, &QPushButton::clicked, this, &MainWindow::on_btnVaccuPowerOn_clicked);
    connect(btnVaccuPowerOff, &QPushButton::clicked, this, &MainWindow::on_btnVaccuPowerOff_clicked);
    connect(ui->btnReadIOStatus, &QPushButton::clicked, this, &MainWindow::on_btnReadIOStatus_clicked);

    //for 4720................................................................
    disconnect(ui->btnSetFitsPath_2, nullptr, this, nullptr);
    disconnect(ui->btnSetReadoutRate_2, nullptr, this, nullptr);
    disconnect(ui->btnPowerDown_2, nullptr, this, nullptr);
    disconnect(ui->btnPowerOn_2, nullptr, this, nullptr);


    connect(ui->btnStartExposure_2, &QPushButton::clicked, this, &MainWindow::on_btnStartExposure_clicked4720);
    connect(ui->btnAbort_2, &QPushButton::clicked, this, &MainWindow::on_btnAbort_clicked4720);
    //connect(ui->btnBrowsePath_2, &QPushButton::clicked, this, &MainWindow::on_btnBrowsePath_clicked4720);
    connect(ui->btnPowerDown_2, &QPushButton::clicked, this, &MainWindow::on_btnPowerDown_clicked4720);
    connect(ui->btnPowerOn_2, &QPushButton::clicked, this, &MainWindow::on_btnPowerOn_clicked4720);
    //connect(ui->btnShutterOff_2, &QPushButton::clicked, this, &MainWindow::on_btnShutterOff_clicked);
    //connect(ui->btnShutterOn_2, &QPushButton::clicked, this, &MainWindow::on_btnShutterOn_clicked);
    connect(ui->btnSetFitsPath_2, &QPushButton::clicked, this, &MainWindow::on_btnSetFitsPath_clicked4720);
    connect(ui->btnSetReadoutRate_2, &QPushButton::clicked, this, &MainWindow::on_btnSetReadoutRate_clicked4720);
    // 初始化进度条定时器
    progressTimer4720 = new QTimer(this);
    progressTimer4720->setInterval(200); // 200ms更新一次进度
    connect(progressTimer4720, &QTimer::timeout, this, [this](){
        updateExposureProgress4720();
    });

    // 初始化进度条
    ui->ExposureprogressBar_2->setRange(0, 100);
    ui->ExposureprogressBar_2->setValue(0);


     //for 4720................................................................


    // 初始化进度条定时器
    progressTimer = new QTimer(this);
    progressTimer->setInterval(200); // 200ms更新一次进度
    connect(progressTimer, &QTimer::timeout, this, [this](){
        updateExposureProgress();
    });

    // 初始化进度条
    ui->ExposureprogressBar->setRange(0, 100);
    ui->ExposureprogressBar->setValue(0);

    // 连接序列完成信号
    connect(this, &MainWindow::sequenceFinished, this, &MainWindow::onSequenceFinished);

    // 初始化序列定时器
    sequenceTimer = new QTimer(this);
    sequenceTimer->setSingleShot(true);

    connect(sequenceTimer, &QTimer::timeout, this, &MainWindow::processSequenceNextFrame);
    disconnect(ui->btnSetFitsPath, nullptr, this, nullptr);
    disconnect(ui->btnStartSequence, nullptr, this, nullptr);
    disconnect(ui->btnStopSequence, nullptr, this, nullptr);
    connect(ui->btnStartSequence, &QPushButton::clicked, this, &MainWindow::on_btnStartSequence_clicked);
    connect(ui->btnStopSequence, &QPushButton::clicked, this, &MainWindow::on_btnStopSequence_clicked);
    // 初始化FITS路径为BIN路径
    //fitsSavePath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
    //ui->lineEditFitsPath->setText(fitsSavePath);
    // 连接新按钮的信号槽
    connect(ui->btnSetFitsPath, &QPushButton::clicked, this, &MainWindow::on_btnSetFitsPath_clicked);


    disconnect(ui->btnSetTemp_2, nullptr, this, nullptr);
    connect(ui->btnSetTemp_2, &QPushButton::clicked, this, &MainWindow::onSetTemperature);


    // 连接信号槽

    disconnect(ui->sendTempCommandBtn, nullptr, this, nullptr);

    connect(ui->sendTempCommandBtn, &QPushButton::clicked, this, &MainWindow::onSendTempCommand);

    // 连接信号槽

    connect(ui->checkboxShowFits, &QCheckBox::toggled, this, &MainWindow::onCheckboxShowFitsToggled);

    // 在MainWindow构造函数中
    m_alarmCheckTimer = new QTimer(this);
    m_alarmCheckTimer->setInterval(5000); // 每秒检查一次
    connect(m_alarmCheckTimer, &QTimer::timeout, this, &MainWindow::checkAllAlarms);
    m_alarmCheckTimer->start();

    m_heartbeatTimer.setSingleShot(false);
    connect(&m_heartbeatTimer, &QTimer::timeout, [this]() {
        if (!m_isRegistered) {
            LOG_GENERAL("No heartbeat response from MCU received, attempting to re-register....");
            onLinkToCameraClicked(); // 自动重试
        } else {
            // 正常心跳状态下更新最后一次接收时间
            m_lastHeartbeatTime = QDateTime::currentDateTime();
        }

        // 超过30秒无心跳视为断开
        if (m_lastHeartbeatTime.secsTo(QDateTime::currentDateTime()) > 30) {
            m_isRegistered = false;
            LOG_GENERAL("Heartbeat lost; the connection may have been disconnected.");
        }
    });


    ui->loopCountSpinBox->setEnabled(false);
    connect(ui->loopCheckBox, &QCheckBox::stateChanged, this, &MainWindow::onLoopCheckBoxStateChanged);

    // 指示灯相关状态检查定时器 (每500ms检查一次)
    m_statusCheckTimer = new QTimer(this);
    connect(m_statusCheckTimer, &QTimer::timeout, this, &MainWindow::checkCameraConnectionStatus);
    m_statusCheckTimer->start(500);

    // 状态指示灯初始化状态记录
    m_lastStatusTime["master"] = QDateTime::currentMSecsSinceEpoch();
    for (int i = 0; i < 4; ++i) {
        QString slaveId = QString("%1").arg(i);
        m_lastStatusTime[slaveId] = QDateTime::currentMSecsSinceEpoch();
        m_slaveBoardStatus[slaveId] = false;
    }

    // 添加配置按钮到菜单栏
    QMenu *configMenu = menuBar()->addMenu("Configuration");
    QAction *networkConfigAction = configMenu->addAction("Network Settings");
    connect(networkConfigAction, &QAction::triggered, this, &MainWindow::showNetworkConfigDialog);

    // 创建历史任务下拉菜单
    m_historyComboBox = new QComboBox(this);
    m_historyComboBox->setEditable(false);
    m_historyComboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    m_historyComboBox->setMinimumWidth(200);

    // 添加标签和下拉菜单到工具栏
    QToolBar* historyToolBar = addToolBar("History");
    historyToolBar->addWidget(new QLabel("拍摄历史:", this));
    historyToolBar->addWidget(m_historyComboBox);

    // 连接信号槽
    connect(m_historyComboBox, QOverload<int>::of(&QComboBox::activated),
            this, &MainWindow::onHistorySelected);

    loadHistoryFromFile();

    m_connectionCheckTimer = new QTimer(this);
    m_connectionCheckTimer->setInterval(5000); // 每秒检查一次
    connect(m_connectionCheckTimer, &QTimer::timeout, this, &MainWindow::checkMCUConnectionStatus);
    m_connectionCheckTimer->start();

    // 添加标签和下拉菜单到工具栏
   // QMenu *coolerconfigMenu = menuBar()->addMenu("CoolerConfiguration");
    //QToolBar* coolerControBar = addToolBar("Cooler Control");
    //coolerControBar->addWidget(new QLabel("制冷机状态:", this));

    // 创建工具栏按钮
    m_toggleCoolerPanelAction = new QAction(QIcon(":/icons/cooler.png"), "制冷机控制", this);
    m_toggleCoolerPanelAction->setCheckable(false);
    connect(m_toggleCoolerPanelAction, &QAction::toggled, this, &MainWindow::toggleCoolerControlPanel);

    // 创建工具栏
    m_coolerToolBar = addToolBar("制冷机控制");
    m_coolerToolBar->setObjectName("CoolerToolBar");
    m_coolerToolBar->addAction(m_toggleCoolerPanelAction);

    // 创建控制面板（初始隐藏）
    m_coolerControlPanel = new QWidget(this);
    QVBoxLayout* panelLayout = new QVBoxLayout(m_coolerControlPanel);
    panelLayout->setContentsMargins(5, 5, 5, 5);

    // 添加温度设置控件
    QFormLayout* tempLayout = new QFormLayout();
    m_tempSetSpinBox = new QDoubleSpinBox();
    m_tempSetSpinBox->setRange(-273.15, 50.0);
    m_tempSetSpinBox->setValue(-196.0);
    tempLayout->addRow("目标温度(℃):", m_tempSetSpinBox);
    panelLayout->addLayout(tempLayout);

    // 添加电压设置控件
    QFormLayout* voltLayout = new QFormLayout();
    m_voltSetSpinBox = new QDoubleSpinBox();
    m_voltSetSpinBox->setRange(0.0, 50.0);
    m_voltSetSpinBox->setValue(35.0);
    voltLayout->addRow("驱动电压(V):", m_voltSetSpinBox);
    panelLayout->addLayout(voltLayout);

    // 添加控制按钮
    QHBoxLayout* btnLayout = new QHBoxLayout();
    QPushButton* powerOnBtn = new QPushButton("启动");
    QPushButton* powerOffBtn = new QPushButton("停止");
    QPushButton* applyBtn = new QPushButton("应用");
    btnLayout->addWidget(powerOnBtn);
    btnLayout->addWidget(powerOffBtn);
    btnLayout->addWidget(applyBtn);
    panelLayout->addLayout(btnLayout);

    // 将控制面板添加到工具栏
    QWidget* spacer = new QWidget();
    spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    //m_coolerToolBar->addWidget(spacer);
    //m_coolerToolBar->addWidget(m_coolerControlPanel);
    m_coolerControlPanel->setVisible(false);

    // 连接信号槽
    connect(powerOnBtn, &QPushButton::clicked, this, [this](){ sendCoolerCommand("$power=1"); });
    connect(powerOffBtn, &QPushButton::clicked, this, [this](){ sendCoolerCommand("$power=0"); });
    connect(applyBtn, &QPushButton::clicked, this, &MainWindow::applyCoolerSettings);
    // 设置工具栏样式
    m_coolerToolBar->setStyleSheet(R"(
    QToolBar {
        background: #f0f0f0;
        border-bottom: 1px solid #ccc;
        spacing: 5px;
    }
    QToolButton {
        padding: 3px;
    }
    )");

    // 设置控制面板样式
    m_coolerControlPanel->setStyleSheet(R"(
    QWidget {
        background: #f8f8f8;
        border: 1px solid #ddd;
        border-radius: 3px;
        padding: 5px;
    }
    QDoubleSpinBox {
        min-width: 80px;
        max-width: 120px;
    }
    QPushButton {
        min-width: 60px;
        padding: 3px;
    }
    )");


    QToolBar* coolerStatusBar = addToolBar("cooler");
    coolerStatusBar->addWidget(new QLabel("制冷机状态:", this));


    // 创建制冷机状态下拉框
    m_coolerStatusCombo = new QComboBox(this);
    m_coolerStatusCombo->setObjectName("coolerStatusCombo");
    m_coolerStatusCombo->setEditable(false);
    m_coolerStatusCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    m_coolerStatusCombo->setMinimumWidth(300);
    m_coolerStatusCombo->setPlaceholderText("制冷机状态");

    m_coolerStatusCombo->setStyleSheet(R"(
    QComboBox {
        font-family: 'Courier New';
        font-size: 10pt;
        min-height: 24px;
        background: #f5f5f5;
    }
    QComboBox QAbstractItemView {
        min-width: 500px;
        background: white;
        border: 1px solid #ccc;
        font-family: 'Courier New';
        font-size: 10pt;
    }
    QComboBox QAbstractItemView::item {
        padding: 2px 5px;
        border-bottom: 1px solid #eee;
    }
    QComboBox QAbstractItemView::item:selected {
        background: #e0f7fa;
    }
    )");

    // 设置等宽字体保证对齐
    m_coolerStatusCombo->setFont(QFont("Courier New", 9));
    //QDockWidget* dock = new QDockWidget("制冷机状态", this);
    //dock->setWidget(m_coolerStatusCombo);
    //addDockWidget(Qt::RightDockWidgetArea, dock);

    coolerStatusBar->addWidget(m_coolerStatusCombo);

    // 添加到界面
    //ui->statusbar->addPermanentWidget(m_coolerStatusCombo);
    //ui->tabWidget->addTab(m_coolerStatusCombo);

    // 初始化定时器
    m_coolerStatusTimer.setInterval(2000); // 2秒刷新一次
    connect(&m_coolerStatusTimer, &QTimer::timeout,
            this, &MainWindow::updateCoolerStatusDisplay);
    m_coolerStatusTimer.start();
    //检查FITS路径是否以挂载路径开头
    connect(ui->lineEditFitsPath, &QLineEdit::textEdited, this, &MainWindow::checkFitsPathMount);
    connect(ui->btnSetFitsPath, &QPushButton::clicked, this, [this](){ checkFitsPathMount(); });

    //清空报警日志
    connect(ui->clearAlarmButton, &QPushButton::clicked, this, &MainWindow::onClearAlarmButtonClicked);

    // 初始化4720 power状态监控
    statusWatcher = new QFileSystemWatcher(this);
    statusCheckTimer = new QTimer(this);
    statusCheckTimer->setInterval(1000); // 1秒检查一次

    // 连接信号槽
    connect(statusWatcher, &QFileSystemWatcher::fileChanged, this, &MainWindow::check4720PowerStatus);
    connect(statusCheckTimer, &QTimer::timeout, this, &MainWindow::check4720PowerStatus);

    // 设置监控文件
    QString statusFile = "/home/csst/PS_mosaic/camera.status";
    if(QFile::exists(statusFile)) {
        statusWatcher->addPath(statusFile);
        check4720PowerStatus(); // 立即检查一次
    }
    statusCheckTimer->start();


    initializeNetwork();
}

MainWindow::~MainWindow()
{   // 停止定时器
    m_logFlushTimer.stop();

    // 关闭所有日志文件
    QMutexLocker locker(&m_logMutex);
    for (auto category : m_logFiles.keys()) {
        // 写入关闭日志
        *m_logStreams[category] << QString("[%1] 程序正常退出\n")
                                       .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"));

        m_logStreams[category]->flush();
        m_logFiles[category]->flush();

        delete m_logStreams[category];
        m_logFiles[category]->close();
        delete m_logFiles[category];
    }

    saveHistoryToFile();
    cleanupConversionProcesses();

    dataUpdateTimer->stop();
    // vacuumCheckTimer->stop();
    progressTimer->stop();
    sequenceTimer->stop();
    exposureTimer->stop();
    // m_logTimer.stop();
    m_logFlushTimer.stop();
    //autoUpdateTimer->stop();
    //vacuumUpdateTimer->stop();

    delete dataUpdateTimer;
    // delete vacuumCheckTimer;
    delete progressTimer;
    delete sequenceTimer;
    delete exposureTimer;
    //delete autoUpdateTimer;
    //delete vacuumUpdateTimer;

    if (m_autoUpdateLogFile.isOpen()) {
        m_autoUpdateLogFile.close();
    }
    if (m_logFile.isOpen()) {
        LOG_GENERAL("The program exits normally.");
        m_logFile.close();
    }
    delete ui;
}


void MainWindow::initializeUI()
{
    ui->checkBoxDump->setChecked(true);
    ui->checkBoxPinning->setChecked(true);
    ui->checkboxShowFits->setChecked(true);

     ui->textEditCameraLog->setReadOnly(true);
    ui->textEditSecondLog->setReadOnly(true);
     ui->textEditCameraLog->clear();
    ui->textEditSecondLog->clear();
     // 设置不同的样式来区分两个日志框
    ui->textEditCameraLog->setStyleSheet("background-color: #f0f0f0;");
    ui->textEditSecondLog->setStyleSheet("background-color: #f8f8f8;");
    qApp->setStyleSheet("QCheckBox { font-size: 11pt; }");
    // ui->lblCameraStatus_2->setText("IDLE");
    //  ui->lblCameraStatus_2->setStyleSheet("background-color: green; color: white;");
    ui->lblCurrentTemp_2->setText(QString::number(hwStatus.currentTemp, 'f', 2) + " °C");
    ui->lblCurrentTemp_3->setText(QString::number(hwStatus.currentTemp, 'f', 2) + " °C");
    ui->lblVacuumAlert_2->setText("NORMAL");
    ui->lblVacuumAlert_2->setStyleSheet("color: green; font-weight: bold;");
    // 初始化读出速度选择下拉框
    ui->comboBoxReadoutRate->clear();
    ui->comboBoxReadoutRate->addItem("1M", 1);
    ui->comboBoxReadoutRate->addItem("2M", 0);

    ui->comboBoxReadoutRate->addItem("512K", 2);
    ui->comboBoxReadoutRate->addItem("256K", 3);
    // 添加comBoxframetype初始化
    ui->comBoxframetype->addItem("sci (sc)", "sc");
    ui->comBoxframetype->addItem("bs", "bs");
    ui->comBoxframetype->addItem("dk", "dk");
    ui->comBoxframetype->addItem("ts", "ts");
    ui->comBoxframetype->addItem("sf", "sf");
    ui->comBoxframetype->addItem("df", "df");
    ui->comBoxframetype->addItem("fs", "fs");
    // 添加bin to fits转换方式选择
    //ui->comboConversionMethod->addItem("Python脚本");
    //ui->comboConversionMethod->addItem("C++原生");
    //connect(ui->comboConversionMethod, QOverload<int>::of(&QComboBox::currentIndexChanged),
    // this, &MainWindow::updateConversionMethod);
    // 温度图控制面板
    QWidget *tempControlPanel = new QWidget(this);
    QHBoxLayout *tempControlLayout = new QHBoxLayout(tempControlPanel);

    QLabel *tempTimeLabel = new QLabel("Time Range(Min):", this);
    QSpinBox *tempTimeSpinBox = new QSpinBox(this);
    tempTimeSpinBox->setObjectName("tempTimeRange");
    tempTimeSpinBox->setRange(1, 60);
    tempTimeSpinBox->setValue(60);
    tempTimeSpinBox->setSuffix(" Min");
    tempTimeLabel->setStyleSheet("QLabel {"
                                 "font-size: 12pt;"  // 字体大小
                                 "min-width: 120px;" // 最小宽度
                                 "min-height: 25px;" // 最小高度
                                 "}");

    // 设置SpinBox样式
    tempTimeSpinBox->setStyleSheet("QSpinBox {"
                                   "font-size: 12pt;"
                                   "min-width: 120px;"
                                   "min-height: 25px;"
                                   "}");

    tempControlLayout->addWidget(tempTimeLabel);
    tempControlLayout->addWidget(tempTimeSpinBox);
    tempControlLayout->addStretch(); // 添加伸缩因子使控件左对齐

    // 将温度控制面板添加到温度图上方
    ui->tempChartLayout->insertWidget(0, tempControlPanel);

    // 真空度图控制面板
    QWidget *vacuumControlPanel = new QWidget(this);
    QHBoxLayout *vacuumControlLayout = new QHBoxLayout(vacuumControlPanel);

    QLabel *vacuumTimeLabel = new QLabel("Time Range(Min):", this);
    QSpinBox *vacuumTimeSpinBox = new QSpinBox(this);
    vacuumTimeSpinBox->setObjectName("vacuumTimeRange");
    vacuumTimeSpinBox->setRange(1, 60);
    vacuumTimeSpinBox->setValue(30);
    vacuumTimeSpinBox->setSuffix(" Min");
    vacuumTimeLabel->setStyleSheet("QLabel {"
                                   "font-size: 12pt;"  // 字体大小
                                   "min-width: 120px;" // 最小宽度
                                   "min-height: 25px;" // 最小高度
                                   "}");

    // 设置SpinBox样式
    vacuumTimeSpinBox->setStyleSheet("QSpinBox {"
                                     "font-size: 12pt;"
                                     "min-width: 120px;"
                                     "min-height: 25px;"
                                     "}");

    vacuumControlLayout->addWidget(vacuumTimeLabel);
    vacuumControlLayout->addWidget(vacuumTimeSpinBox);
    vacuumControlLayout->addStretch(); // 添加伸缩因子使控件左对齐

    // 将真空度控制面板添加到真空度图上方
    ui->vacuumChartLayout->insertWidget(0, vacuumControlPanel); // 假设真空度图有自己的布局

    // 连接信号槽
    connect(tempTimeSpinBox, QOverload<int>::of(&QSpinBox::valueChanged),
            this, &MainWindow::updateTempChartTimeRange);
    connect(vacuumTimeSpinBox, QOverload<int>::of(&QSpinBox::valueChanged),
            this, &MainWindow::updateVacuumChartTimeRange);
}

